<template>
    <div class="comp-html-editor" v-loading.fullscreen="loading">
        <div class="comp-html-editor__body" ref="body"></div>
        <div class="comp-html-editor__foot" v-if="$slots.foot || $scopedSlots.foot">
            <slot name="foot"></slot>
        </div>
    </div>
</template>

<script>
    import mixin from "../mixin";
    import { string, int, selectFile } from "../util";
    import Quill from "quill";
    import env from "@/env";
    export default {
        name: "comp-html-editor",
        mixins: [mixin],
        emits:['uploadProgress'],
        props: {
            editing: { type: Boolean, default: false },
            content: { type: String, default: null },
        },
        data: () => ({
            loading: false,
            baseApiUrl:env.xhrPrefix
        }),
        methods: {
            onClickToolbarMedia(type) {
                if (this.loading) return;
                let media = [
                    { type: "link", name: "附件", accept: "*/*", size: 50 * 1048576, sizeText: "50MB" },
                    { type: "image", name: "图片", accept: "image/*", size: 50 * 1048576, sizeText: "50MB" },
                    { type: "video", name: "视频", accept: "video/*", size: 3000 * 1048576, sizeText: "3000MB" },
                    // { type: "audio", name: "音频", accept: "audio/*", size: 10 * 1048576, sizeText: "10MB" },
                ].find((media) => media.type === type);
                let [editor, range] = [this.editor, this.editor.getSelection()];
                console.log('html-content上传进度',this)
                let callback = (file) => {
                    this.loading = true;
                    this.plugins.user.uploadFile(file, type,(e)=>{
                        console.log('html-content上传进度',e)
                        // 上传进度
                        this.$emit('uploadProgress',e)
                    }).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            if(type == 'link'){
                                console.log('file',file)
                                // 先插入文本
                                editor.insertText(range.index + range.length, file.name);
                                // 然后设置文本为超链接
                                editor.formatText(range.index + range.length, file.name.length, 'link', env.xhrPrefixMiniApp+"/user/sysStorage/getFile/"+res.data.id+"?id="+res.data.id);
                            }else{
                                editor.insertEmbed(range.index + range.length, type, env.xhrPrefixMiniApp+"/user/sysStorage/getFile/"+res.data.id+"?id="+res.data.id);
                            }

                            editor.setSelection(range.index + range.length + 1, 0);
                        } else {
                            this.plugins.modal.alert(media.name + "上传失败", res.code + "：" + res.msg, "error");
                        }
                    });
                };
                if (media) selectFile(media.accept, this.$el).then((file) => {
                    console.log('文件大小',file.size)
                    if (file.size > media.size) this.plugins.modal.toast(media.name + "过大，不能大于" + media.sizeText + "哦，请重新选择。", "error");
                    else callback(file);
                });
            },
            getContent() {
                let content = this.editing ? this.editor.root.innerHTML : this.content;
                if (content === "<p><br></p>") content = "";
                return content;
            },
            destroy() {
                this.$refs.body.childNodes.forEach((node) => node.nodeType === 1 && node.remove());
                this.editor = null;
            },
            init() {
                if (this.editor) this.destroy();
                let container = ((node) => this.$refs.body.appendChild(node))(document.createElement("div"));
                let menus = [
                    [
                        { "font": ["Default", "SimSun", "FangSong", "SimHei", "KaiTi"] },
                        { "size": ["16px", "18px", "20px", "24px", "28px", "14px", "12px"] },
                    ],
                    [
                        "bold",
                        "italic",
                        "underline",
                        "strike",
                        { "color": [] },
                        { "background": [] },
                    ],
                    [
                        { "align": "" },
                        { "align": "center" },
                        { "align": "right" },
                        { "align": "justify" },
                    ],
                    [
                        { "indent": "-1" },
                        { "indent": "+1" },
                    ],
                    [
                        { "list": "ordered" },
                        { "list": "bullet" },
                    ],
                    [
                        "link",
                        "image",
                        "video",
                        // "audio",
                    ],
                ];
                let editor = this.editor = new Quill(container, {
                    theme: "snow",
                    modules: { toolbar: this.editing ? menus : null },
                    placeholder: "请输入",
                    readOnly: !this.editing,
                });
                let toolbar = editor.getModule("toolbar");
                let toolbarAudioBtn = container.parentNode.querySelector(".ql-toolbar .ql-formats .ql-audio");
                if (toolbarAudioBtn) toolbarAudioBtn.innerHTML = `<svg viewbox="0 0 18 18"><ellipse class="ql-fill" cx="10.5" cy="14" rx="2.5" ry="2"/><path class="ql-stroke" d="M12,14V3c0,1.5,3,2.021,3,5"/><path class="ql-fill" d="M7,4A5,5,0,0,0,7,14a3.191,3.191,0,0,1,3-2.957V5.023A4.955,4.955,0,0,0,7,4ZM4.06,8.412a0.5,0.5,0,0,1-.49.4,0.485,0.485,0,0,1-.1-0.01,0.5,0.5,0,0,1-.393-0.588A3.98,3.98,0,0,1,6.216,5.079a0.5,0.5,0,0,1,.2.98A2.985,2.985,0,0,0,4.06,8.412ZM7,10A1,1,0,1,1,8,9,1,1,0,0,1,7,10Z"/></svg>`;
                if (toolbar) ['link',"image", "video", "audio"].forEach((type) => toolbar.addHandler(type, () => this.onClickToolbarMedia(type)));
                editor.root.innerHTML = this.content;
            },
        },
        created() {
            const Font = Quill.import("formats/font");
            const Size = Quill.import("formats/size");
            const BlockEmbed = Quill.import("blots/block/embed");
            class Video extends BlockEmbed {
                static create(value) {
                    let node = super.create();
                    node.setAttribute("style", "width:100%;");
                    node.setAttribute("controls", true);
                    node.setAttribute("controlslist", "nodownload nofullscreen");
                    node.setAttribute("preload", "metadata");
                    node.setAttribute("src", string(value));
                    return node;
                };
                static value(node) {
                    return node.getAttribute("src");
                };
            };
            class Audio extends BlockEmbed {
                static create(value) {
                    let node = super.create();
                    node.setAttribute("style", "width:100%;");
                    node.setAttribute("controls", true);
                    node.setAttribute("controlslist", "nodownload");
                    node.setAttribute("preload", "metadata");
                    node.setAttribute("src", string(value));
                    return node;
                };
                static value(node) {
                    return node.getAttribute("src");
                };
            };
            Font.whitelist = ["Default", "SimSun", "FangSong", "SimHei", "KaiTi"];
            Size.whitelist = ["14px", "16px", "18px", "20px", "24px", "28px"];
            Video.className = "ql-video";
            Video.blotName = "video";
            Video.tagName = "video";
            Audio.className = "ql-audio";
            Audio.blotName = "audio";
            Audio.tagName = "audio";
            Quill.register("formats/font", Font, true);
            Quill.register("formats/size", Size, true);
            Quill.register("formats/video", Video, true);
            Quill.register("formats/audio", Audio, true);
        },
    };
</script>

<style lang="scss">
    @import "~quill/dist/quill.snow.css";

    .comp-html-editor {
        display: flex;
        flex-flow: column nowrap;
        justify-content: flex-start;
        align-items: stretch;
        height: 300px;
    }

    .comp-html-editor__body {
        flex: 1 1 0;
        display: flex;
        flex-flow: column nowrap;
        justify-content: flex-start;
        align-items: stretch;
    }

    .comp-html-editor__foot {
        flex: 0 0 auto;
        display: flex;
        flex-direction: row nowrap;
        justify-content: center;
        align-items: center;
        margin-top: 20px;
    }

    .ql-editor {
        .ql-audio {
            display: block;
            max-width: 100%;
        }
    }

    .ql-toolbar.ql-snow {
        flex: 0 0 auto;
        display: flex;
        flex-flow: row wrap;
        justify-content: flex-start;
        align-items: flex-start;
        align-content: flex-start;
        border: solid 1px #ddd;
        padding: 0;
        background-color: white;

        .ql-formats {
            flex: 0 0 auto;
            display: flex;
            flex-flow: row nowrap;
            justify-content: flex-start;
            align-items: center;
            margin: 0;
            background-color: #f6f6f6;

            button {
                flex: 0 0 auto;
                padding: 0;
                width: 28px;
                height: 28px;

                svg {
                    margin: 5px;
                    width: 18px;
                    height: 18px;
                }
            }

            .ql-picker {
                flex: 0 0 auto;
                display: flex;
                flex-flow: row nowrap;
                justify-content: flex-start;
                align-items: center;
                width: auto;
                height: auto;

                .ql-picker-label {
                    flex: 0 0 auto;
                    padding: 0 24px 0 8px;
                    width: auto;
                    height: 28px;
                    line-height: 28px;

                    svg {
                        right: 2px;
                    }
                }

                &.ql-font {
                    .ql-picker-label,
                    .ql-picker-item {
                        font-family: sans-serif;
                    }

                    .ql-picker-label[data-value="Default"],
                    .ql-picker-item[data-value="Default"] {
                        &:before {
                            content: "默认字体";
                        }
                    }

                    .ql-picker-label[data-value="SimSun"],
                    .ql-picker-item[data-value="SimSun"] {
                        &:before {
                            font-family: "SimSun", "STSong";
                            content: "宋体";
                        }
                    }

                    .ql-picker-label[data-value="FangSong"],
                    .ql-picker-item[data-value="FangSong"] {
                        &:before {
                            font-family: "FangSong", "STFangsong";
                            content: "仿宋";
                        }
                    }

                    .ql-picker-label[data-value="SimHei"],
                    .ql-picker-item[data-value="SimHei"] {
                        &:before {
                            font-family: "SimHei", "STHeiti";
                            content: "黑体";
                        }
                    }

                    .ql-picker-label[data-value="KaiTi"],
                    .ql-picker-item[data-value="KaiTi"] {
                        &:before {
                            font-family: "KaiTi", "STKaiti";
                            content: "楷体";
                        }
                    }
                }

                &.ql-size {
                    .ql-picker-label[data-value="12px"],
                    .ql-picker-item[data-value="12px"] {
                        &:before {
                            content: "12px";
                        }
                    }

                    .ql-picker-label[data-value="14px"],
                    .ql-picker-item[data-value="14px"] {
                        &:before {
                            content: "14px";
                        }
                    }

                    .ql-picker-label[data-value="16px"],
                    .ql-picker-item[data-value="16px"] {
                        &:before {
                            content: "16px";
                        }
                    }

                    .ql-picker-label[data-value="18px"],
                    .ql-picker-item[data-value="18px"] {
                        &:before {
                            content: "18px";
                        }
                    }

                    .ql-picker-label[data-value="20px"],
                    .ql-picker-item[data-value="20px"] {
                        &:before {
                            content: "20px";
                        }
                    }

                    .ql-picker-label[data-value="24px"],
                    .ql-picker-item[data-value="24px"] {
                        &:before {
                            content: "24px";
                        }
                    }

                    .ql-picker-label[data-value="28px"],
                    .ql-picker-item[data-value="28px"] {
                        &:before {
                            content: "28px";
                        }
                    }
                }

                &.ql-color,
                &.ql-background {
                    .ql-picker-label {
                        padding: 0;

                        svg {
                            margin: 5px;
                            width: 18px;
                            height: 18px;
                            right: auto;
                        }
                    }
                }
            }

            &:after {
                display: none;
            }
        }

        & + .ql-container.ql-snow {
            border-top-width: 0;
        }
    }

    .ql-container.ql-snow {
        flex: 1 1 0;
        border: solid 1px #ddd;
        height: auto;
        background-color: white;

        .ql-editor {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            padding: 10px;
            color: #333;
            font-size: 16px;
            font-family: sans-serif;
            font-weight: normal;
            line-height: 1.5;
            overflow-x: hidden;
            overflow-y: auto;

            .ql-font-Default {
                font-family: inherit;
            }

            .ql-font-SimSun {
                font-family: "SimSun", "STSong";
            }

            .ql-font-FangSong {
                font-family: "FangSong", "STFangsong";
            }

            .ql-font-SimHei {
                font-family: "SimHei", "STHeiti";
            }

            .ql-font-KaiTi {
                font-family: "KaiTi", "STKaiti";
            }

            .ql-size-12px {
                font-size: 12px;
            }

            .ql-size-14px {
                font-size: 14px;
            }

            .ql-size-16px {
                font-size: 16px;
            }

            .ql-size-18px {
                font-size: 18px;
            }

            .ql-size-20px {
                font-size: 20px;
            }

            .ql-size-24px {
                font-size: 24px;
            }

            .ql-size-28px {
                font-size: 28px;
            }

            &.ql-blank {
                &:before {
                    display: none;
                }
            }
        }
    }
</style>
